from datetime import datetime, timedelta

from django.db import models
from django.utils import timezone


class AccessTokenManager(models.Manager):
    def verify_token(self, token):
        """校验token"""
        now = timezone.now()
        return self.filter(token=token, exp__gt=now, revoked_at__isnull=True).exists()

    def get_token(self, token):
        """获取token"""
        now = timezone.now()
        return self.get(token=token, exp__gt=now, revoked_at__isnull=True)


class AccessToken(models.Model):
    """Token"""
    objects = AccessTokenManager()

    app = models.TextField(blank=True, verbose_name='名称')
    token = models.TextField()

    sub = models.TextField()
    exp = models.DateTimeField()

    # 如果退出登录，这里记住退出时间
    revoked_at = models.DateTimeField(null=True, default=None)

    def revoke(self):
        if self.revoked_at is None:
            self.revoked_at = timezone.now()
            self.save(update_fields=['revoked_at'])
